<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main r_main" :class="isCheck?'':'show'">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-tabs v-model="activeName">
          <el-tab-pane label="设备保养" name="first">
            <el-form-item label="保养工单号" prop="code">
              <el-input v-model="formData.code" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="保养计划单号" prop="planCode">
              <el-input v-model="formData.planCode" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="保养设备" prop="bookName">
              <el-input v-model="formData.bookName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="设备位置" prop="location">
              <el-input v-model="formData.location" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="保养级别" prop="levelName">
              <el-input v-model="formData.levelName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="计划保养时间" prop="">
              <el-input v-model="formData.planTime" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="班次" prop="shiftLabel">
              <el-input v-model="formData.shiftLabel" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="保养模板" prop="templateName">
              <el-input v-model="formData.templateName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="备注" prop="remark" class="double">
              <el-input v-model="formData.remark" type="textarea" placeholder="暂无" />
            </el-form-item>
            <el-divider />
            <el-form-item label="保养人员" prop="">
              <el-input v-model="formData.checkPersonName" placeholder="暂无" disabled />
            </el-form-item>

            <el-form-item label="维保班组" prop="baseMaintenanceName">
              <el-input v-model="formData.baseMaintenanceName" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item label="保养费用（元）">
              <el-input v-model="formData.maintainMoney" type="number" oninput="if(value<0)value=0" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="保养完成时间" prop="completeTime">
              <el-date-picker
                v-if="isCheck"
                v-model="formData.completeTime"

                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
              <el-input v-else v-model="formData.completeTime" placeholder="暂无" disabled />
            </el-form-item>
            <el-form-item />
            <el-form-item />
            <div ref="table_container" class="table_container draggableTable addRow_table">
              <el-table
                ref="table"
                :data="tableData"
                stripe
                border
                row-key="id"
                style="width: 99.9%"
              >
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <el-form label-position="left" class="expand_container">
                      <el-form-item label="保养结果" class="expand_radio">
                        <el-radio v-if="isCheck" v-model="props.row.result" :label="1"><svg-icon icon-class="勾" /></el-radio>
                        <el-radio v-if="isCheck" v-model="props.row.result" :label="0"><svg-icon icon-class="叉" /></el-radio>
                        <div v-if="!isCheck" class="show">
                          <svg-icon v-if="props.row.result==1" icon-class="勾" />
                          <svg-icon v-if="props.row.result==0" icon-class="叉" />
                        </div>
                      </el-form-item>
                      <el-form-item label="现场照片" class="expand_file file double">
                        <FileManageFull
                          :file-names="props.row.docName"
                          :file-real-names="props.row.docRealName"
                          :file-urls="props.row.docUrl"
                          :row-index="props.$index"
                          :readonly="!isCheck"
                          @fileName="setFileName"
                        />
                      </el-form-item>
                      <el-form-item label="保养记录" class="double">
                        <el-input v-if="isCheck" v-model="props.row.description" type="textarea" placeholder="请输入" />
                        <div v-else class="show">{{ props.row.description }}</div>
                      </el-form-item>
                      <el-form-item label="备注" class="double">
                        <el-input
                          v-if="isCheck"
                          v-model="props.row.remark"
                          type="textarea"
                          maxlength="200"
                          show-word-limit
                          placeholder="请输入"
                        />
                        <div v-else class="show">{{ props.row.remark }}</div>
                      </el-form-item>
                    </el-form>
                  </template>
                </el-table-column>
                <el-table-column
                  type="index"
                  width="50"
                  label="序号"
                />
                <el-table-column prop="name" label="保养项目">
                  <template slot-scope="scope">
                    <DivTextarea :row-value="scope.row.name" />
                  <!-- <el-input v-model="scope.row.name" style="margin:10px 0;" type="textarea" autosize readonly /> -->
                  </template>
                </el-table-column>
                <el-table-column prop="content" label="保养内容">
                  <template slot-scope="scope">
                    <DivTextarea :row-value="scope.row.content" />
                  <!-- <el-input v-model="scope.row.content" style="margin:10px 0;" type="textarea" autosize readonly /> -->
                  </template>
                </el-table-column>
                <el-table-column prop="way" label="保养方式">
                  <template slot-scope="scope">
                    <DivTextarea :row-value="scope.row.way" />
                  <!-- <el-input v-model="scope.row.way" style="margin:10px 0;" type="textarea" autosize readonly /> -->
                  </template>
                </el-table-column>
                <el-table-column prop="time" label="时间 ( S )" width="80">
                  <template slot-scope="scope">
                    <DivTextarea :row-value="scope.row.time" />
                  <!-- <el-input v-model="scope.row.time" style="margin:10px 0;" type="textarea" autosize readonly /> -->
                  </template>
                </el-table-column>
                <el-table-column prop="criterion" label="判断标准">
                  <template slot-scope="scope">
                    <DivTextarea :row-value="scope.row.criterion" />
                  <!-- <el-input v-model="scope.row.criterion" style="margin:10px 0;" type="textarea" autosize readonly /> -->
                  </template>
                </el-table-column>
                <el-table-column prop="time" label="至少上传张数" width="140">
                  <template slot-scope="scope">
                    <!-- <el-input v-model="scope.row.time" style="margin:10px 0;" type="textarea" autosize readonly /> -->
                    <DivTextarea :row-value="scope.row.minPage?scope.row.minPage+'':''" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="附件"
                  min-width="120"
                >
                  <template slot-scope="scope">
                    <FileManage
                      :file-names.sync="scope.row.fileName"
                      :file-real-names.sync="scope.row.fileRealName"
                      :file-urls.sync="scope.row.fileUrl"
                      :readonly="true"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="添加备件" name="second">
            <div class="formItem_header">
              <div class="formItem_header_operate">
                <a class="formItem_header_operate_item" @click="addRecord">
                  <svg-icon icon-class="新增" />
                  <div class="item_name">添加</div>
                </a>
                <a class="formItem_header_operate_item" @click="importSpareParts">
                  <svg-icon icon-class="导入" />
                  <div class="item_name">导入</div>
                </a>
                <a class="formItem_header_operate_item delete" @click="removeRow">
                  <svg-icon icon-class="删除" />
                  <div class="item_name">删除</div>
                </a>
              </div>
            </div>
            <div ref="table_container2" class="table_container">
              <el-table
                ref="table"
                :data="spareList"
                stripe
                border
                style="width: 99.9%"
                :header-cell-class-name="headerCellClassName"
                @selection-change="selectionChange1"
              >
                <el-table-column type="selection" align="center" width="50" />
                <el-table-column
                  prop="spareCode"
                  label="备件编码"
                  min-width="120"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="spareName"
                  label="备件名称"
                  min-width="100"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="spareModel"
                  label="规格型号"
                  min-width="100"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="numberUnitLabel"
                  label="备件单位"
                  min-width="100"
                />
                <el-table-column
                  prop="deviceSpareWarehouseName"
                  label="仓库"
                  min-width="100"
                />
                <el-table-column
                  prop="batch"
                  label="批号"
                  min-width="100"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="inventoryNumber"
                  label="库存数量"
                  :min-width="SETTINGS.settings_decimalDigits_length"
                />
                <el-table-column
                  prop="useNumber"
                  label="使用数量"
                  :min-width="SETTINGS.settings_decimalDigits_length"
                >
                  <template slot-scope="scope">
                    <el-input v-if="isCheck" v-model="scope.row.useNumber" style="" placeholder="请输入" />
                    <div v-else class="show">{{ scope.row.useNumber }}</div>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="isCheck"
                  prop="operate"
                  width="60"
                />
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <div v-if="isCheck" class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="save">保存</el-button>
      <el-button @click.stop="submit">提交</el-button>
    </div>
  </div>
</template>

<script>
import DivTextarea from '@/components/JLink/common/DivTextarea.vue'
import { addOrUpdate, getInfo } from '@/api/equipmentManage/equipmentMaintain/maintainRecord'
import addRecord from '../../sparePartsManagement/sparePartsCollocation/chooseSpareParts.vue'
import ImportData from '@/components/JLink/common/ImportData'
import { importMethod } from '@/api/equipmentManage/sparePart/outWarehouse'
import { mapGetters } from 'vuex'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    isCheck: {},
    defaultValue: {}
  },
  component: {
    DivTextarea
  },
  data() {
    const validateCompleteTime = (rule, value, callback) => {
      if (this.type == 'save') {
        callback()
      }
      if (this.type == 'submit') {
        if (!value) {
          callback(new Error('保养完成时间不能为空'))
        } else {
          callback()
        }
      }
    }
    return {
      pageId: '保养备件',
      formData: {
        id: undefined,
        code: undefined,
        planCode: undefined,
        bookId: undefined,
        bookName: undefined,
        location: undefined,
        checkPersonId: undefined,
        levelName: undefined,
        planTime: undefined,
        baseMaintenanceName: undefined,
        outFormCode: undefined,
        templateName: undefined,
        shiftLabel: undefined,
        completeTime: '',
        remark: undefined,
        checkPersonName: undefined,
        isSubmit: '1',
        planId: undefined,
        maintainMoney: '',
        spareList: [],
        detailList: []
      },
      num: 1,
      isSubmit: 1,
      type: '',
      roleOptions: [],
      activeName: 'first',
      tableData: [],
      tableHeight: '400',
      tableHeight2: '500',
      userOptions: [],
      userOptions2: [],
      selectionsAll1: [],
      nativeSelect: '',
      spareList: [],
      disabled: false,
      rules: {
        planTime: [
          { required: true, message: '计划保养时间不能为空', trigger: 'change' }
        ],
        completeTime: [
          { required: true, validator: validateCompleteTime, trigger: 'change' }
        ],
        taskMode: [
          { required: true, message: '任务启动方式不能为空', trigger: 'change' }
        ],
        period: [
          { required: true, message: '保养周期不能为空', trigger: 'change' }
        ],
        periodUnit: [
          { required: true, message: '周期单位不能为空', trigger: 'change' }
        ],
        checkPersonId: [
          { required: true, message: '保养人员不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  computed: {
    ...mapGetters([
      'notificationId'
    ])
  },
  methods: {
    headerCellClassName(data) {
      if (['useNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key] || ''
        })
        this.spareList = res.data.spareList
        this.tableData = res.data.detailList
      })
    },
    save() {
      if (this.spareList.filter(item => item.useNumber && !this.SETTINGS.reg_no_zero.test(item.useNumber)).length > 0) {
        this.$message.warning('使用数量输入不正确')
        return
      } else if (this.spareList.filter(item => item.useNumber && Number(item.useNumber) > Number(item.inventoryNumber)).length > 0) {
        this.$message.warning('使用数量不能大于库存数量')
        return
      }
      this.type = 'save'
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.id = this.id
          this.spareList.forEach(item => {
            if (item.isOldList !== true) {
              item.id = null
            }
          })
          this.formData.spareList = this.$deepClone(this.spareList)
          this.formData.detailList = this.$deepClone(this.tableData)
          this.formData.isSubmit = 0
          addOrUpdate({ ...this.formData, isFromMsg: this.notificationId > 0 ? '1' : '0' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$store.dispatch('notification/changeId', 0)
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    submit() {
      if (this.spareList.filter(item => !item.useNumber).length > 0) {
        this.$message.warning('使用数量不能为空')
        return
      } else if (this.spareList.filter(item => item.useNumber && !this.SETTINGS.reg_no_zero.test(item.useNumber)).length > 0) {
        this.$message.warning('使用数量输入不正确')
        return
      } else if (this.tableData.filter(item => !item.result && item.result != 0).length > 0) {
        this.$message.warning('保养项目中保养结果不能为空')
        return
      } else if (this.spareList.filter(item => item.useNumber && Number(item.useNumber) > Number(item.inventoryNumber)).length > 0) {
        this.$message.warning('使用数量不能大于库存数量')
        return
      } else if (this.tableData.filter(item => (item.docRealName ? item.docRealName.split(',').length : 0) < item.minPage).length > 0) {
        const obj = this.tableData.filter(item => (item.docRealName ? item.docRealName.split(',').length : 0) < item.minPage)[0]
        this.$message({
          message: `保养项目${obj.name}的现场照片张数不能少于${obj.minPage}张`,
          type: 'warning'
        })
        return
      }
      this.type = 'submit'
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.id = this.id
          this.spareList.forEach(item => {
            if (item.isOldList !== true) {
              item.id = null
            }
          })
          this.formData.spareList = this.$deepClone(this.spareList)
          this.formData.detailList = this.$deepClone(this.tableData)
          this.formData.isSubmit = 1
          addOrUpdate({ ...this.formData, isFromMsg: this.notificationId > 0 ? '1' : '0' }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$store.dispatch('notification/changeId', 0)
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    setFileName(...data) {
      const cacheTableData = this.$deepClone(this.tableData)
      cacheTableData[data[3]].docName = data[0]
      cacheTableData[data[3]].docRealName = data[1]
      cacheTableData[data[3]].docUrl = data[2]
      this.tableData = cacheTableData
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 选择物料后从弹窗取出来的数据
    addMaterial(data) {
      this.spareList = data
    },
    addRecord() { // 打开选择备件
      this.$layer.iframe({// 弹框
        content: {
          content: addRecord, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            defaultValue: {
              parentId: 0,
              parentName: '根目录'
            },
            selectedRow: this.spareList
          }
        },
        area: ['1200px', '680px'],
        title: '选择备件信息', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 获取保养模版数据
    showTemplate(data) {
      this.tableData = data
    },
    // 获取保养设备id
    showEquipment(data) {
      this.formData.bookId = data.id
    },

    removeRow(row) { // 删除行
      this.selectionsAll1.forEach(item => {
        this.spareList.splice(this.spareList.indexOf(item), 1)
      })
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.data) {
          this.spareList = []
          res.data.forEach(item => {
            item.batchInventoryId = item.batchId
            if (Number(item.useNumber) > Number(item.batchInventoryNumber)) {
              this.$message.warning('导入的数据中存在出库数量大于库存数量的数据,请修改后重新导入')
              return false
            } else {
              this.spareList.push(item)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.el-form-item__label {
  width: 140px !important;
}
//一姐让改的
// /deep/ .el-textarea__inner{
//   border: none !important;
//   background: none;
// }
/deep/ .accessory{
  color: #387bfc;
}
.main_main{
  padding-top: 0px;
  .formItem_header{
    justify-content: flex-end;
    align-items: flex-start;
    height: 40px;
  }
  /deep/ .el-tabs{
    width: 100%;
    height: 100%;
  }
  .form_padding{
    display: flex;
    flex-wrap: wrap;

    /deep/ .el-form-item{
      margin-right: 0px;
    }
  }
}
.main_main.show{
  /deep/  .el-tabs__header.is-top{
    margin-bottom: 0px;
  }
  .form_padding{
    margin-top: 20px;
  }
}
.expand_radio{
  /deep/ .el-form-item__content{
    text-align: left;
  }
}
.expand_container{
  .el-form-item{
    margin-bottom: 10px;
  }
  .expand_file{
    margin-bottom: 0px;
  }

}
/deep/ .el-table th.el-table__cell>.cell{
  position:unset;
}
/deep/ .el-tabs__header{
  width: 100% !important;
  position: absolute;
  z-index: 99999;
}
/deep/ .el-tabs__content{
  margin-top: 50px;
}
.expand_radio{
  padding-top: 20px;
}
/deep/.is-scrolling-none {
  margin-bottom: 8px !important;
}
</style>
